import { defineStore } from 'pinia';
import { ApiService } from 'src/services/api';

export const useCoursesStore = defineStore('COURSES', {
  state: () => ({
    records: [],
    totalRecords: 0,
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchRecords(payload) {
      try {
        this.loading = true;
        this.error = null;
        
        console.log("CoursesStore fetchRecords - 请求URL:", payload.url);
        console.log("CoursesStore fetchRecords - 请求完整参数:", payload);
        
        // 使用payload中的参数构建请求
        let url = payload.url;
        
        // 创建一个新的选项对象，确保params不被覆盖
        const options = { params: {} };
        
        // 如果有分页参数，克隆它们以避免引用问题
        if (payload.params) {
          // 深度复制参数对象
          options.params = JSON.parse(JSON.stringify(payload.params));
          console.log("CoursesStore - 处理后的分页参数:", options.params);
        }
        
        console.log("CoursesStore - 最终请求选项:", options);
        const response = await ApiService.get(url, options);
        console.log("CoursesStore - API响应状态:", response.status);
        console.log("CoursesStore - API响应数据:", response.data);
        
        // 确保正确更新状态
        if (response.data && response.data.records) {
          if (payload.merge && this.records.length) {
            // 合并记录（用于无限滚动）
            this.records = [...this.records, ...response.data.records];
          } else {
            // 替换记录
            this.records = response.data.records;
          }
          this.totalRecords = response.data.totalRecords || 0;
          
          // 记录每次请求返回的记录
          console.log("CoursesStore - 返回记录:", {
            记录数组长度: this.records.length,
            记录ID列表: this.records.map(r => r.course_id),
            总记录数: this.totalRecords
          });
        } else {
          console.warn("CoursesStore - API响应缺少records字段:", response.data);
        }
        
        console.log("CoursesStore更新完成，记录数:", this.records.length);
        console.log("CoursesStore总记录数:", this.totalRecords);
        return this.records;
      } catch (error) {
        console.error("CoursesStore获取记录失败:", error);
        this.error = error.message || '获取数据失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 重置记录
    resetRecords() {
      this.records = [];
      this.totalRecords = 0;
    },
    
    // 添加新记录
    addRecord(record) {
      this.records.push(record);
      this.totalRecords++;
    },
    
    // 更新记录
    updateRecord(id, updatedRecord) {
      const index = this.records.findIndex(record => record.course_id === id);
      if (index !== -1) {
        this.records[index] = { ...this.records[index], ...updatedRecord };
      }
    },
    
    // 删除记录
    deleteRecord(id) {
      const index = this.records.findIndex(record => record.course_id === id);
      if (index !== -1) {
        this.records.splice(index, 1);
        this.totalRecords--;
      }
    },

    // 向store添加直接加载方法
    async loadPageData(url, params) {
      try {
        this.loading = true;
        this.error = null;
        
        console.log("CoursesStore loadPageData - 请求URL:", url);
        console.log("CoursesStore loadPageData - 请求参数:", params);
        
        // 构建请求选项
        const options = { params };
        
        console.log("CoursesStore loadPageData - 请求选项:", options);
        const response = await ApiService.get(url, options);
        console.log("CoursesStore loadPageData - 响应状态:", response.status);
        
        // 处理响应数据
        if (response.data && response.data.records) {
          this.records = response.data.records;
          this.totalRecords = response.data.totalRecords || 0;
          
          console.log("CoursesStore loadPageData - 加载完成:", {
            records: this.records.length,
            totalRecords: this.totalRecords
          });
          
          return {
            success: true,
            data: this.records
          };
        } else {
          console.warn("CoursesStore loadPageData - API响应缺少records字段");
          return {
            success: false,
            message: "API响应缺少records字段"
          };
        }
      } catch (error) {
        console.error("CoursesStore loadPageData - 加载失败:", error);
        this.error = error.message || "加载失败";
        return {
          success: false,
          message: this.error
        };
      } finally {
        this.loading = false;
      }
    }
  }
}); 